/*
 *        ds18b20获取温度值
 *
 *        2022-02-13
 *
 *
 */


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

#define dir_fixed_head	 "/sys/bus/w1/devices/"
#define dir_fixed_end "/w1_slave"
#define dir_fixed_if "28-"

int main(int arc , char **arv)
{
	char 		pathnamep[100]="";
	char		wendu_s[50]="";
	char		*wendu_sp;
	char		*wendu_p;
	double		wendu_f ;
	off_t  		size_off;
	int 		rv = -1;

	int		fd_wendu = -1;
	DIR		*dirp;
	struct dirent	*direntp;
	struct stat	statp;


	if( (dirp =  opendir(dir_fixed_head)) == NULL)
	{
		printf("opendir %s error: %s \n",dir_fixed_head,strerror(errno));

		goto cleanup;
	}
	while( (direntp = readdir(dirp)) != NULL)
	{
		if( strncmp(dir_fixed_if,direntp->d_name,3) == 0)
		{
			printf("discovery file : %s \n" ,direntp->d_name);
			rv = 0;

			strcat(pathnamep,dir_fixed_head);
			strcat(pathnamep,direntp->d_name);
			strcat(pathnamep,dir_fixed_end);
			
			printf("pathnamep : %s\n",pathnamep);			
			break;			
		}
	}
	closedir(dirp);

	if( rv == -1 )
	{
		printf("no files found\n");
		
		goto cleanup;
	}

	if( (fd_wendu = open(pathnamep,	O_RDONLY)) == -1)
	{
		printf("open file failure : \n",strerror(errno));
		goto cleanup;
	}

#if 1
	fstat(fd_wendu,&statp);
	printf(" seze : %ld \n",(long int)statp.st_size);

	if( lseek(fd_wendu,statp.st_size-4027,SEEK_SET) == -1)
	{
		printf("seek error");
		goto cleanup;
	}
	
	if( ( rv = read(fd_wendu,wendu_s,5)) != 5)
	{
		printf("read failed\n");
		printf("read : %d \n  wendu_s :%s",rv ,wendu_s);
		goto cleanup;
	}
	else
	{
		wendu_f = atof(wendu_s);
		wendu_f /= 1000;
		printf("temperature : %2.2f°C\n\n",wendu_f);
	}
	
#endif 

#if 0

	if( ( rv = read(fd_wendu,wendu_s,4096)) == 0)
	{
		printf("read failed\n");
		goto cleanup;
	}
	else
	{
		wendu_sp = wendu_s;
		wendu_p = strsep(&wendu_sp,"=");
		wendu_p = strsep(&wendu_sp,"=");
		wendu_f = atof(wendu_sp);
		wendu_f /= 1000;

		printf("temperature : %2.2f°C\n\n",wendu_f);
	}
#endif	

cleanup:
	
	if(fd_wendu >=0)
	{
		close(fd_wendu);
	}

	return 0;
}
